<template>
  <div class="location-attendance">
    <div class="page-header">
      <i class="el-icon-location"></i>
      创建位置签到
      <div class="header-desc">设置签到地点、范围和有效时间，学生需要在指定范围内完成签到</div>
    </div>
    <el-form :model="form" :rules="rules" ref="form" label-width="120px" class="attendance-form">
      <el-form-item label="签到标题" prop="title" required>
        <el-input
          v-model="form.title"
          placeholder="请输入签到标题，如：第1节课签到">
        </el-input>
      </el-form-item>
      <el-form-item label="选择班级" prop="classroomId" required>
        <el-select
          v-model="form.classroomId"
          placeholder="请选择班级"
          style="width: 100%">
          <el-option
            v-for="item in classrooms"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="签到范围" prop="radius" required>
        <el-input-number
          v-model="form.radius"
          :min="50"
          :max="500"
          :step="10"
          style="width: 200px"
          controls-position="right">
        </el-input-number>
        <span class="unit-text">米</span>
        <div class="input-tip">
          <i class="el-icon-info"></i>
          学生需要在以当前位置为中心，半径{{ form.radius }}米的范围内完成签到
        </div>
      </el-form-item>
      <el-form-item label="有效时长" prop="duration" required>
        <el-input-number
          v-model="form.duration"
          :min="5"
          :max="120"
          :step="5"
          style="width: 200px"
          controls-position="right">
        </el-input-number>
        <span class="unit-text">分钟</span>
        <div class="input-tip">
          <i class="el-icon-time"></i>
          签到将在{{ form.duration }}分钟后自动结束
        </div>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime" required>
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="当前位置">
        <div class="location-info">
          <span v-if="currentLocation" class="location-text">
            经度：{{ currentLocation.longitude }}
            <br>
            纬度：{{ currentLocation.latitude }}
          </span>
          <span v-else class="no-location">
            未获取位置
          </span>
          <el-button
            type="primary"
            icon="el-icon-location"
            @click="getCurrentLocation"
            :loading="locating"
            class="location-btn">
            获取位置
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="loading"
          :disabled="!currentLocation"
          class="submit-btn">
          创建签到
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'LocationAttendance',
  data() {
    return {
      form: {
        title: '',
        classroomId: '',
        latitude: '',
        longitude: '',
        radius: 100,
        duration: 30,
        startTime: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入签到标题', trigger: 'blur' },
          { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        classroomId: [
          { required: true, message: '请选择班级', trigger: 'change' }
        ],
        radius: [
          { required: true, message: '请输入签到范围', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请输入有效时长', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ]
      },
      classrooms: [],
      loading: false,
      locating: false,
      currentLocation: null
    }
  },
  created() {
    this.getClassrooms()
  },
  methods: {
    async getClassrooms() {
      try {
        const res = await this.$http.get('/api/teacher/classroom/list')
        this.classrooms = res.data.records
      } catch (error) {
        this.$message.error('获取班级列表失败')
      }
    },
    async getCurrentLocation() {
      this.locating = true
      try {
        // 使用浏览器原生定位
        const position = await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject, {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
          })
        })

        const lng = position.coords.longitude
        const lat = position.coords.latitude

        this.currentLocation = {
          longitude: lng,
          latitude: lat
        }
        this.form.longitude = lng
        this.form.latitude = lat

      } catch (error) {
        console.error('获取位置失败:', error)
        this.$message.error('获取位置失败，请检查浏览器定位权限')
      } finally {
        this.locating = false
      }
    },
    async handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.loading = true
          let res
          try {
            // 构建完整的表单数据
            const submitData = {
              ...this.form,
              startTime: this.form.startTime || new Date().toISOString()
            }

            res = await this.$http.post('/api/teacher/attendance/location', submitData)
            if (res.code === 1) {
              this.$message.success('位置签到创建成功')
              this.$router.push('/attendance/list')
            } else {
              this.$message.error(res.msg)
            }
          } catch (error) {
            if (error.response && error.response.data) {
              this.$message.error(error.response.data.msg)
            } else {
              this.$message.error('创建位置签到失败')
            }
          } finally {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.location-attendance {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.page-header i {
  margin-right: 8px;
  color: #409EFF;
}

.header-desc {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
  margin-left: 20px;
}

.attendance-form {
  max-width: 800px;
}

.unit-text {
  margin-left: 10px;
  color: #606266;
}

.input-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.input-tip i {
  margin-right: 4px;
}

.location-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.location-text {
  color: #303133;
  line-height: 1.8;
}

.no-location {
  color: #909399;
}

.location-btn {
  margin-left: 20px;
}

.submit-btn {
  width: 200px;
}
</style>
